<template>
  <q-page class="wrapBox" v-loading="loading">
    <div class="nav">

      <el-breadcrumb separator="/" v-if="modelStore().showModelId === 0">
        <el-breadcrumb-item>
          <el-image src="/svgs/algManagementIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>模型服务</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'model-manage' }">训练作业</el-breadcrumb-item>
        <el-breadcrumb-item><span style=" color: #333;">新建训练作业</span></el-breadcrumb-item>
      </el-breadcrumb>
      <el-breadcrumb separator="/" v-else>
        <el-breadcrumb-item>
          <el-image src="/svgs/algManagementIcon.svg" style="width: 17px;margin-top: 2px" fit />
        </el-breadcrumb-item>
        <el-breadcrumb-item>算法服务</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'alg-manage' }">算法管理</el-breadcrumb-item>
        <el-breadcrumb-item><span style=" color: #333;">创建训练作业</span></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content">
      <div class="title">基本信息</div>
      <div class="contentBox">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="180px" class="demo-ruleForm typeBox"
          status-icon>
          <el-form-item label="训练任务名称:" prop="title">
            <el-input v-model.trim="ruleForm.title" placeholder="请输入训练任务名称" spellcheck="false" style="width: 350px" />
          </el-form-item>
          <el-form-item label="任务描述:" prop="description">
            <el-input v-model.trim="ruleForm.description" type="textarea" show-word-limit maxlength="100"
              spellcheck="false" placeholder="请输入" :rows="5" style="width: 350px" />
          </el-form-item>
          <el-form-item label="特征集选择:" prop="featureset_id">
            <el-select v-model="ruleForm.featureset_id" class="m-2" placeholder="请选择特征集名称" v-load-more="getMoreData">
              <el-option v-for="item in featuresDataList.results" :key="item.title" :label="item.title" :value="item.id"
                @click="chooseFeatures(item.id)" />
              <div v-if="loadingMoreState" class="selectMoreData">
                <el-icon class="is-loading">
                  <Loading />
                </el-icon>加载更多
              </div>
            </el-select>
          </el-form-item>
          <el-form-item label="算法来源:" prop="sources" v-if="modelStore().showModelId === 0">
            <el-radio-group v-model="ruleForm.sources" @change="handleRadioChange">
              <el-radio-button label="myData" >我的算法</el-radio-button>
              <el-radio-button label="otherData">AutoML</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="请选择算法:" prop="modelId" v-if="ruleForm.sources !== 'otherData'">
            <el-select v-model="ruleForm.modelId" class="m-2" placeholder="请选择算法">
              <el-option v-for="item in allAlg" :key="item.id" :label="item.title" :value="item.id" @click="chooseAlg" />
            </el-select>
          </el-form-item>
          <el-form-item label="超参:" prop="ml_parameters" v-if="showArr.length > 0 && ruleForm.sources !== 'otherData'">
            <el-row :gutter="20" style="width: 100%;">
              <el-col :span="9">
                <div class="grid-content ep-bg-purple borderBox" v-for="(item, index) in parametersObj" :key="index">
                  {{ item }}
                </div>
              </el-col>
              <el-col :span="1" style="text-align: center;">
                <div v-for="(item, index) in parametersObj" :key="index">=</div>
              </el-col>
              <el-col :span="9">
                <div class="grid-content ep-bg-purple borderBox rightBox" v-for="(item, index) in parametersDefault"
                  :key="index">
                  <input spellcheck="false" class="inputBox" type="text" :value="item.default"
                    @blur="changeText($event, index)" @keyup.enter="changeText($event, index)">
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="train_data:" prop="train_data" v-if="ruleForm.featureset_id && ruleForm.sources === 'otherData' && treeData.length > 0 ">
            <el-tree :data="treeData" :props="defaultProps" ref="tree" show-checkbox node-key="id" check-strictly="true"  @check-change="handleCheckChange"></el-tree>
          </el-form-item>
          <el-form-item label="test_data:" prop="test_data" v-if="ruleForm.featureset_id && ruleForm.sources === 'otherData' && treeData.length > 0 ">
            <el-tree :data="treeData" :props="defaultProps" ref="treeTwo" show-checkbox node-key="id" @check-change="handleCheckChangeTwo"></el-tree>
          </el-form-item>
          <el-form-item label="check_point_name:" prop="check_point_name" v-if="ruleForm.featureset_id && ruleForm.sources === 'otherData' && treeData.length > 0 ">
            <el-tree :data="treeData" :props="defaultProps" ref="treeThree" show-checkbox node-key="id" @check-change="handleCheckChangeThree"></el-tree>
          </el-form-item>
          <el-form-item label="target label:" prop="target_column" v-if="ruleForm.sources === 'otherData'" style="width: 500px">
            <el-input v-model.trim="ruleForm.target_column" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="evaluation metric:" prop="metric" v-if="ruleForm.sources === 'otherData'">
            <el-select v-model="ruleForm.metric">
              <el-option label="precision" value="precision" />
              <el-option label="pearsonr" value="pearsonr" />
              <el-option label="accuracy" value="accuracy" />
              <el-option label="mcc" value="mcc" />
              <el-option label="roc_auc" value="roc_auc" />
              <el-option label="balanced_arraracy" value="balanced_arraracy" />
              <el-option label="rmse" value="rmse" />
            </el-select>
          </el-form-item>
          <el-form-item label="training precision:" prop="mode" v-if="ruleForm.sources === 'otherData'">
            <el-select v-model="ruleForm.mode" placeholder="please select your zone">
              <el-option label="best_quality" value="best_quality" />
              <el-option label="medium_quality" value="medium_quality" />
              <el-option label="manual" value="manual" />
            </el-select>
          </el-form-item>
          <el-form-item label="模型选择:" prop="tabular" v-if="ruleForm.sources === 'otherData'">
            <el-select v-model="ruleForm.tabular" placeholder="please select your zone">
              <el-option label="深度学习" :value="0" />
              <el-option label="机器学习 (SVM等)" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="max epochs:" prop="max_epochs" v-if="ruleForm.sources === 'otherData'"
            style="width: 500px">
            <el-input v-model.trim.number="ruleForm.max_epochs" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="learing rate schedule:" prop="lr_schedule" v-if="ruleForm.sources === 'otherData'">
            <el-select v-model="ruleForm.lr_schedule" placeholder="please select your zone">
              <el-option label="cosine_decay" value="cosine_decay" />
              <el-option label="polynomial_decay" value="polynomial_decay" />
              <el-option label="linear_decay" value="linear_decay" />
            </el-select>
          </el-form-item>
          <el-form-item label="Instant delivery:" v-if="ruleForm.sources === 'otherData'">
            <el-switch v-model="ruleForm.delivery" />
          </el-form-item>
          <el-form-item label="HPO seacher:" v-if="ruleForm.delivery && ruleForm.sources === 'otherData'">
            <el-radio-group v-model="ruleForm.searcher" label="size control" @change="handleSearchChange">
              <el-radio-button label="bayes">bayes</el-radio-button>
              <el-radio-button label="grid">grid</el-radio-button>
              <el-radio-button label="random">random</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="trail number:" prop="num_trials"
            v-if="ruleForm.delivery && (ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') && ruleForm.sources === 'otherData'"
            style="width: 500px">
            <el-input v-model.trim.number="ruleForm.num_trials"
              :placeholder="ruleForm.searcher === 'random' ? '请输入次数:至少2次' : '请输入'" />
          </el-form-item>
          <el-form-item label="lr_decay:"
            v-if="ruleForm.delivery && (ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') && ruleForm.sources === 'otherData'">
            min
            <el-form-item prop="lr_decay_min" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.lr_decay_min" @blur="handleInputBlur('lr_decay_min')"
                placeholder="请输入次数: 0-1" />
            </el-form-item>
            ~
            max
            <el-form-item prop="lr_decay_max" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.lr_decay_max" @blur="handleInputBlur('lr_decay_max')"
                placeholder="请输入次数: 0-1" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="lr_decay:" prop="lr_decay"
            v-if="ruleForm.delivery && ruleForm.searcher === 'grid' && ruleForm.sources === 'otherData'"
            style="display: flex;flex-direction: row">
            <el-input v-model.trim="addValueData.lr_decay" @blur="handleBlur('lr_decay')"
              placeholder="请输入:例: 1e-2,1e-3,1e-5" spellcheck="false" style="width: 200px" />
            <el-button type="primary" style="margin-left: 20px" @click="addValueHandle('lr_decay')">add</el-button>
            <el-input v-model.trim="ruleForm.lr_decay" class="addValue" spellcheck="false"></el-input>
            <span v-if="errorOnlrDecayInput" class="el-form-item__error">lr_decay 不能为空{}</span>
          </el-form-item>
          <el-form-item label="learning rate:"
            v-if="ruleForm.delivery && (ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') && ruleForm.sources === 'otherData'">
            min
            <el-form-item prop="lrMin" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.lrMin" placeholder="请输入次数: 0-1" @blur="handleInputBlur('lrMin')" />
            </el-form-item>
            ~
            max
            <el-form-item prop="lrMax" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.lrMax" placeholder="请输入次数: 0-1" @blur="handleInputBlur('lrMax')" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="learning rate:" prop="lr"
            v-if="ruleForm.delivery && ruleForm.searcher === 'grid' && ruleForm.sources === 'otherData'"
            style="display: flex;flex-direction: row">
            <el-input v-model.trim="addValueData.lr" @blur="handleBlur('lr')" placeholder="请输入:例: 1e-2,1e-3,1e-5"
              spellcheck="false" style="width: 200px" />
            <el-button type="primary" style="margin-left: 20px" @click="addValueHandle('lr')">add</el-button>
            <el-input v-model.trim="ruleForm.lr" class="addValue" spellcheck="false"></el-input>
            <span v-if="errorOnlrInput" class="el-form-item__error">lr 不能为空{}</span>
          </el-form-item>
          <el-form-item label="weight decay:"
            v-if="ruleForm.delivery && (ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') && ruleForm.sources === 'otherData'">
            min
            <el-form-item prop="weight_decay_min" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.weight_decay_min" placeholder="请输入次数: 0-1" spellcheck="false"
                @blur="handleInputBlur('weight_decay_min')" />
            </el-form-item>
            ~
            max
            <el-form-item prop="weight_decay_max" style="margin: 0 10px">
              <el-input v-model.trim="ruleForm.weight_decay_max" placeholder="请输入次数: 0-1" spellcheck="false"
                @blur="handleInputBlur('weight_decay_max')" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="weight decay:" prop="weight_decay"
            v-if="ruleForm.delivery && ruleForm.searcher === 'grid' && ruleForm.sources === 'otherData'">
            <el-input v-model.trim="addValueData.weight_decay" @blur="handleBlur('weight_decay')"
              placeholder="请输入:例: 1e-3,1e-3,1e-5" style="width: 200px" spellcheck="false" />
            <el-button type="primary" style="margin-left: 20px" @click="addValueHandle('weight_decay')">add</el-button>
            <el-input v-model.trim="ruleForm.weight_decay" class="addValue" spellcheck="false"></el-input>
            <span v-if="errorOnWeightDecayInput" class="el-form-item__error">weight_decay 不能为空{}</span>
          </el-form-item>
          <el-form-item label="optim_type:" prop="resource"
            v-if="ruleForm.delivery && ruleForm.sources === 'otherData' && ruleForm.sources === 'otherData'">
            <el-radio-group v-model="ruleForm.optim_type">
              <el-radio label="sgd" />
              <el-radio label="adam" />
              <el-radio label="adamw" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="batch size：" prop="batch_size"
            v-if="ruleForm.delivery && (ruleForm.searcher == 'bayes' || ruleForm.searcher == 'random') && ruleForm.sources === 'otherData'">
            <el-input v-model.trim="ruleForm.batch_size"
              @input="ruleForm.batch_size = ruleForm.batch_size.replace(/\D/g, '');" spellcheck="false" type="textarea"
              show-word-limit maxlength="100" placeholder="请输入" :rows="5" style="width: 500px" />
          </el-form-item>
          <el-form-item label="batch size：" prop="batch_size"
            v-if="ruleForm.delivery && ruleForm.searcher == 'grid' && ruleForm.sources === 'otherData'">
            <el-input v-model.trim="addValueData.batch_size"
              @input="addValueData.batch_size = addValueData.batch_size.replace(/\D/g, '');" placeholder="请输入"
              style="width: 200px" spellcheck="false" />
            <el-button type="primary" style="margin-left: 20px" @click="addValueHandle('batch_size')">add</el-button>
            <el-input v-model.trim="ruleForm.batch_size" class="addValue" spellcheck="false"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="content" style="margin-top: 20px">
      <div class="title">训练任务/资源配置</div>
      <div class="contentBox">
        <el-form ref="ruleFormRefTwo" :model="sourceRuleForm" :rules="sourceRules" label-width="130px"
          class="demo-ruleForm typeBox" style="max-width: 50%;" status-icon>
          <el-form-item label="集群队列：" prop="queue_name">
            <el-select v-model="sourceRuleForm.queue_name" class="m-2" placeholder="请选择集群队列">
              <el-option v-for="item in clusterQueueData.results" :key="item.name" :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="训练资源：" class="cpuDataBox">
            <template #default>
              <div class="row" style="min-width: 500px;">
                <div class="col">
                  CPU卡数：<el-input spellcheck="false" class="numberInput"
                    oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>32)value=32;if(value<=0)value=null"
                    type="number" v-model="sourceRuleForm.cpu" size="small" style="width: 60px;"></el-input> 核
                </div>
                <div class="col" style="margin-right: -30px;">
                  内存：<el-input class="numberInput" spellcheck="false"
                    oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>1000000000)value=10000000000;if(value<=0)value=null"
                    v-model="sourceRuleForm.memory" size="small" style="width: 60px;"></el-input> M
                </div>
                <div class="col">
                  GPU核数：<el-input class="numberInput" spellcheck="false" v-model="sourceRuleForm.gpu" size="small"
                    style="width: 60px;"></el-input> 核
                </div>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="自动停止：">
            <template #default>
              <div>
                <el-switch v-model="ruleForm.is_auto_stop" />
                <transition name="el-zoom-in-top">
                  <div class="colorBox" v-show="ruleForm.is_auto_stop">
                    时长：<el-input v-model="ruleForm.stop_in_seconds" size="small" @input="inputChange"
                      style="width: 60px;"></el-input> 小时
                    <i>作业时间到最大值会强制停止，若训练未完成可能会造成作业失败</i>
                  </div>
                </transition>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="故障自动重启：">
            <template #default>
              <div>
                <el-switch v-model="ruleForm.is_fail_restart" />
                <transition name="el-zoom-in-top">
                  <div class="colorBox" v-show="ruleForm.is_fail_restart">
                    重启次数： <el-select v-model="ruleForm.restartNum" class="m-2" placeholder="" size="small"
                      style="width: 60px;">
                      <el-option :label="1" :value="1" />
                      <el-option :label="2" :value="2" />
                      <el-option :label="3" :value="3" />
                    </el-select><i>设置后无法更改</i>
                  </div>
                </transition>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="清除缓存：">
            <el-switch v-model="ruleForm.is_clear_conda_cache" />
            <el-tooltip class="box-item" effect="light " content="清除数据缓存" placement="right-start">
              <el-button
                style="transform: scale(.8);transform-origin:left ; margin:0 0 0 5px; font-size: 18px;color: #333;border-color: #333;"
                size="small" circle>?
              </el-button>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </div>
      <div class="row" style="justify-content: end;margin-top: 10px;background-color: #fff;padding: 10px 0 ">
        <el-button v-if="!store.quickStart.quickFlow" @click="resetForm(ruleFormRef)"
          style="background-color: #fff">取消</el-button>
        <el-button v-if="!store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          提交训练
        </el-button>
        <el-button v-if="store.quickStart.quickFlow" type="primary" @click="submitForm(ruleFormRef)">
          下一步
        </el-button>
      </div>
    </div>
  </q-page>
</template>

<script setup lang="ts">

import { ref, reactive, shallowRef, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import {
  getAlgAllList,
  getParameters,
  validateTraining,
  getClusterQueueDataHandle,
  createRuns,
  getAutomlModeId,
  getFeaturesPaths
} from 'src/api/model'
import { Obj } from '@popperjs/core';
import { modelStore } from 'src/stores/model';
import { ElMessage, ElMessageBox } from "element-plus";
import { getFeatureset } from "src/api/dataset";
import { dataSetStore } from 'src/stores/dataSet'
import { putQuickStartFlow } from 'src/api/project'
const store = dataSetStore()
const ruleFormRef = ref();
const ruleFormRefTwo = ref();
const router = useRouter();
const projectId = router.currentRoute.value.params.project_id;
const loading = ref(false);
const treeData = ref([]);
const autoMlId = ref(0);

const errorOnlrDecayInput = ref(false);
const errorOnlrInput = ref(false);
const errorOnWeightDecayInput = ref(false);


const ruleForm = reactive(<any>{
  title: '',
  description: '',
  num_trials: 1,
  mode: '',
  sources: 'myData',
  ml_parameters: {},
  modelId: '',
  featureset_id: '',
  is_fail_restart: false,
  is_clear_conda_cache: false,
  delivery: false,
  batch_size: '',
  optim_type: 'sgd',
  tabular: 0,
  searcher: '', //切换tab
  lr_schedule: '',
  target_column: '',
  max_epochs: 10,
  metric: '',
  test_data: '',
  train_data: '',
  lr: '{}',
  lrMax: '',
  lrMin: '',
  is_auto_stop: false,
  stop_in_seconds: 0,
  lr_decay: '{}',
  lr_decay_min: '',
  lr_decay_max: '',
  weight_decay: '{}',
  weight_decay_min: '',
  weight_decay_max: '',
  check_point_name: ''
});
const validateTrainingTaskName = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('训练任务名称不能为空'))
    return
  }
  let params = {
    title: ruleForm.title
  }
  validateTraining(projectId, params).then(res => {
    if (res.data.exists) {
      callback(new Error('训练任务名称重复'))
    }
    callback()
  }).catch(err => {
    callback(new Error('校验接口报错'))
  })
}

const validateLrDecay = (rule: any, value: any, callback: any) => {
  if (value === '{}') {
    callback(new Error('lr_decay的值不能为空'))
    return
  }
  callback()
}
const validateLr = (rule: any, value: any, callback: any) => {
  if (value === '{}') {
    callback(new Error('lr的值不能为空'))
    return
  }
  callback()
}
const validateWeightDecay = (rule: any, value: any, callback: any) => {
  if (value === '{}') {
    callback(new Error('weight_decay的值不能为空'))
    return
  }
  callback()
}
const validateBatchSize = (rule: any, value: any, callback: any) => {
  if (value === '{}') {
    callback(new Error('batch_size的值不能为空'))
    return
  }
  callback()
}

const rules = reactive<FormRules>({
  title: [
    { required: true, validator: validateTrainingTaskName, trigger: 'blur' }
  ],
  lr: [
    { required: true, validator: validateLr, trigger: 'blur' }
  ],
  lrMax: [
    { required: true, message: 'lrMax值不能为空', trigger: 'blur' }
  ],
  lrMin: [
    { required: true, message: 'lrMin值不能为空', trigger: 'blur' }
  ],
  featureset_id:[
    { required: true, message: '特征集选择不能为空', trigger: 'blur' }
  ],
  ml_parameters: [
    { required: true, message: '', trigger: 'blur' }
  ],
  sources: [
    { required: true, message: '', trigger: 'blur' }
  ],
  mode: [
    { required: true, message: 'mode值不能为空', trigger: 'blur' }
  ],
  tabular: [
    { required: true, message: '模型选择不能为空', trigger: 'blur' }
  ],
  lr_schedule: [
    { required: true, message: 'lr_schedule不能为空', trigger: 'blur' }
  ],
  modelId: [
    { required: true, message: '请选择算法' }
  ],
  metric: [
    { required: true, message: 'metric值不能为空', trigger: 'blur' }
  ],
  num_trials: [
    { required: true, message: 'num_trials值不能为空', trigger: 'blur' }
  ],
  lr_decay: [
    { required: true, validator: validateLrDecay, trigger: 'blur' }
  ],
  lr_decay_min: [
    { required: true, message: 'lr_decay_min值不能为空', trigger: 'blur' }
  ],
  lr_decay_max: [
    { required: true, message: 'lr_decay_max值不能为空', trigger: 'blur' }
  ],
  weight_decay: [
    { required: true, validator: validateWeightDecay, trigger: 'blur' }
  ],
  weight_decay_min: [
    { required: true, message: 'weight_decay_min值不能为空', trigger: 'blur' }
  ],
  weight_decay_max: [
    { required: true, message: 'weight_decay_max值不能为空', trigger: 'blur' }
  ],
  batch_size: [
    { required: true, validator: validateBatchSize, trigger: 'blur' }
  ],
  target_column: [
    { required: true, message: 'target_column值不能为空', trigger: 'blur' }
  ],
  train_data: [
    { required: true, message: 'train_data值不能为空', trigger: 'blur' }
  ],
  test_data: [
    { required: true, message: 'test_data值不能为空', trigger: 'blur' }
  ],
  check_point_name: [
    { required: true, message: 'check_point_name值不能为空', trigger: 'blur' }
  ],
})

const sourceRuleForm = reactive({
  is_auto_stop: false,
  stop_in_seconds: 0,
  is_fail_restart: false,
  restartNum: 1,
  cpu: 1,
  gpu: 1,
  memory: 100,
  featureset_id: '',
  is_clear_conda_cache: false,
  queue_name: ''
})

const sourceRules = reactive<FormRules>({
  title: [
    { required: true, message: '算法名称不能为空', trigger: 'blur' }
  ],
  cpu: [
    { required: true, message: '输入核心数', trigger: 'blur' }
  ],
  queue_name: [
    { required: true, message: '集群队列不能为空' }
  ]
});

const loadingMoreState = ref(false)

const parametersObj = shallowRef()
const parametersDefault = shallowRef()
const showArr = ref([])
const addValueData = ref({
  lr_decay: '',
  batch_size: '',
  lr: '',
  weight_decay: ''
});
//特征集
const pageData = ref({
  page: 1
});
const featuresDataList = reactive({
  count: 0,
  results: <any>[]
})
const debounceTimer = ref(null);
const debounceTimerTwo = ref(null);
const debounceTimerThree = ref(null);
function handleRadioChange(value: any) {
  //切换AutoML的时候请求算法id
  if (value === 'otherData') {
    getAutomlModeId(projectId).then((res: any) => {
      autoMlId.value = res.data.id
    })
  }
}
function handleSearchChange(value: any) {
  if (value === 'bayes' || value === 'random') {
    ruleForm.batch_size = ''
  } else {
    ruleForm.batch_size = '{}'
  }
}
function handleInputBlur(val: string) {
  const inputValue = ruleForm[val];
  const numbers = parseFloat(inputValue);
  if (isNaN(numbers) || numbers < 0 || numbers >= 1) {
    ruleForm[val] = ''; // 清空输入框
  }
}
function handleBlur(val: string) {
  const inputValue = addValueData.value[val];
  const numbers = parseFloat(inputValue);
  if (isNaN(numbers) || numbers < 0 || numbers >= 1 || numbers === 0) {
    addValueData.value[val] = ''; // 清空输入框
  }
}
const addValueHandle = (val: string) => {
  let data = addValueData.value[val];
  if (ruleForm[val] === "{}") {
    ruleForm[val] = `{${data}}`;
  } else {
    ruleForm[val] = ruleForm[val].replace("}", `, ${data}}`);
  }
  addValueData.value[val] = '';
}

chooseFeatureset()
function chooseFeatureset() {
  loading.value = false
  getFeatureset(projectId, pageData.value).then((res: any) => {
    featuresDataList.count = res.data.count
    if (featuresDataList.results.length == 0) {
      featuresDataList.results = res.data.results
    } else {
      featuresDataList.results = featuresDataList.results.concat(res.data.results)
    }
    loadingMoreState.value = false
  }).catch(error => {
    console.log(error)
  })
}
// 下拉懒加载
const getMoreData = async () => {
  if (pageData.value.page < (featuresDataList.count) / 10) {
    loadingMoreState.value = true
    pageData.value.page++
    chooseFeatureset()
  }
}
//集群队列
const clusterQueueData = reactive({
  count: 0,
  results: <any>[]
});
initProject();//项目初始化
function initProject() {
  AlgAllList();
  if (modelStore().showModelId !== 0) {
    ruleForm.modelId = modelStore().showModelId;
    chooseAlg();
  }
  getClusterQueueData();//获取集群队列列表
}

function getClusterQueueData() {
  getClusterQueueDataHandle().then((res: any) => {
    clusterQueueData.count = res.data.count
    clusterQueueData.results = res.data
    loadingMoreState.value = false
  })
}
function changeText(e: any, index: number) {
  parametersDefault.value[index].default = (e.target.value).trim()
  ruleForm.ml_parameters = Object.assign(mergeArr(parametersObj.value, parametersDefault.value))
}
// 处理数组，合并为object
const mergeArr = (arr1: Array<string>, arr2: Array<any>) => {
  let newObj: Obj = {}
  arr1.forEach((item, index) => {
    newObj[item] = arr2[index].default
  })
  return newObj
}
function transform(arr: any) {
  const rootNode = {};

  // 将数组中的每个路径转化为一个嵌套的对象结构
  arr.forEach(path => {
    const parts = path.split('/');
    let currentNode = rootNode;
    parts.forEach((part, index) => {
      if (!currentNode[part]) {
        currentNode[part] = {};
      }
      currentNode = currentNode[part];
    });
  });

  let idCounter = 1;

  function convertToDesiredFormat(node) {
    return Object.entries(node).map(([key, value]) => {
      const id = idCounter++;
      const result = { id, label: key.replace(/-/g, ' ') };
      const children = convertToDesiredFormat(value);
      if (children.length > 0) {
        result.children = children;
      }
      return result;
    });
  }
  return convertToDesiredFormat(rootNode);
}
const tree = ref()
const treeTwo = ref()
const treeThree = ref()
function chooseFeatures(id:number){
  getFeaturesPaths(projectId,id).then( (res:any) =>{
    treeData.value = transform(res.data.results)
  })
}
// 构建节点的绝对路径
const findParentPath = (data, targetId, path = '') => {
  for (const item of data) {
    const newPath = path === '' ? item.label : `${path}/${item.label}`; // 构建当前节点的路径

    if (item.id === targetId) {
      return newPath; // 如果找到目标对象，返回路径
    }

    if (item.children && item.children.length > 0) {
      const found = findParentPath(item.children, targetId, newPath);
      if (found) {
        return found; // 如果在子级中找到目标对象，返回路径
      }
    }
  }

  return null; // 如果未找到目标对象，返回null
};
function handleCheckChange(node: any, checked: any) {
  clearTimeout(debounceTimer.value);
  debounceTimer.value = setTimeout(() => {
    if (checked) {
      ruleForm.train_data = '../' + findParentPath(JSON.parse(JSON.stringify(treeData.value)), JSON.parse(JSON.stringify(node)).id);
      tree.value.setCheckedKeys([node.id]);
    }
  }, 100)
}
function handleCheckChangeTwo(node: any, checked: any) {
  clearTimeout(debounceTimerTwo.value);
  debounceTimerTwo.value = setTimeout(() => {
    if (checked) {
      ruleForm.test_data = '../' + findParentPath(JSON.parse(JSON.stringify(treeData.value)), JSON.parse(JSON.stringify(node)).id);
      treeTwo.value.setCheckedKeys([node.id]);
    }
  })
}
function handleCheckChangeThree(node: any, checked: any) {
  clearTimeout(debounceTimerThree.value);
  debounceTimerThree.value = setTimeout(() => {
    if (checked) {
      ruleForm.check_point_name = '../' + findParentPath(JSON.parse(JSON.stringify(treeData.value)), JSON.parse(JSON.stringify(node)).id);
      treeThree.value.setCheckedKeys([node.id]);
    }
  })
}
const defaultProps = {
  children: 'children',
  label: 'label',
}
function chooseAlg() {
  loading.value = true
  // modelStore().dataset(ruleForm.modelId)
  getParameters(projectId, ruleForm.modelId).then((res: any) => {
    parametersObj.value = Object.keys(res.data)
    parametersDefault.value = Object.values(res.data)
    showArr.value = []
    showArr.value = showArr.value.concat(parametersObj.value)
    ruleForm.ml_parameters = Object.assign(mergeArr(parametersObj.value, parametersDefault.value))
  }).finally(() => {
    loading.value = false
  }).catch(error => {
    console.log(error)
  })
}

//检查每个表单的校验规则
const checkForm = (formName: any) => {
  return new Promise((resolve, reject) => {
    formName.value.validate((valid: boolean) => {
      if (valid) {
        resolve(1);
      } else reject();
    });
  });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  let list = [];
  list.push(checkForm(ruleFormRef), checkForm(ruleFormRefTwo));
  let projectDatas: any;
  if (ruleForm.sources == 'otherData') {
    projectDatas = autoMlId.value;
    ruleForm.modelId = `${autoMlId.value}`;
    if (ruleForm.sources === 'otherData') {
      ruleForm.ml_parameters.target_column = ruleForm.target_column;
      ruleForm.ml_parameters.metric = ruleForm.metric;
      ruleForm.ml_parameters.mode = ruleForm.mode;
      ruleForm.ml_parameters.tabular = ruleForm.tabular;
      ruleForm.ml_parameters.check_point_name = ruleForm.check_point_name;
      ruleForm.ml_parameters.lr_schedule = ruleForm.lr_schedule;
      ruleForm.ml_parameters.test_data = ruleForm.test_data;
      ruleForm.ml_parameters.train_data = ruleForm.train_data;
      if (ruleForm.delivery) {
        ruleForm.ml_parameters.optim_type = ruleForm.optim_type;
        if (ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') {
          ruleForm.ml_parameters.searcher = ruleForm.searcher;
          ruleForm.ml_parameters.num_trials = ruleForm.num_trials;
          ruleForm.ml_parameters.lr_decay = `${ruleForm.lr_decay_min},${ruleForm.lr_decay_max}`;
          ruleForm.ml_parameters.lr = `${ruleForm.lrMin},${ruleForm.lrMax}`;
          ruleForm.ml_parameters.weight_decay = `${ruleForm.weight_decay_min},${ruleForm.weight_decay_max}`;
          ruleForm.ml_parameters.batch_size = Number(ruleForm.batch_size);
        }
        if (ruleForm.searcher === 'grid') {
          ruleForm.ml_parameters.lr = ruleForm.lr && ruleForm.lr.replace(/{|}/g, "");
          ruleForm.ml_parameters.lr_decay = ruleForm.lr_decay && ruleForm.lr_decay.replace(/{|}/g, "");
          ruleForm.ml_parameters.weight_decay = ruleForm.weight_decay && ruleForm.weight_decay.replace(/{|}/g, "");
          ruleForm.ml_parameters.batch_size = 5;
          // // ruleForm.ml_parameters.batch_size = Number(ruleForm.batch_size);
        }
      }
    }
    if (ruleForm.max_epochs) {
      ruleForm.ml_parameters.max_epochs = ruleForm.max_epochs;
    }
    if (ruleForm.tabular === 1 || ruleForm.searcher === 'bayes' || ruleForm.searcher === 'random') {
      delete ruleForm.ml_parameters.check_point_name
    } else {
      ruleForm.ml_parameters.check_point_name = ruleForm.check_point_name
    }
  } else {
    projectDatas = ruleForm.modelId
  }
  //ruleForm.project_id = projectId;

  const { title, description, featureset_id, modelId, is_auto_stop, stop_in_seconds, is_fail_restart, restartNum, is_clear_conda_cache } = ruleForm;
  const { queue_name, cpu, memory, gpu } = sourceRuleForm;
  let submitObj = {
    title,
    description,
    featureset_id,
    modelId,
    queue_name,
    cpu,
    memory,
    gpu,
    is_auto_stop,
    stop_in_seconds,
    is_fail_restart,
    restartNum,
    is_clear_conda_cache,
    ml_parameters: { ...ruleForm.ml_parameters }
  };

  if (ruleForm.searcher === 'grid') {

    if (ruleForm.lr_decay === '{}') {
      errorOnlrDecayInput.value = true
    } else {
      errorOnlrDecayInput.value = false
    }

    if (ruleForm.lr_decay === '{}') {
      errorOnlrInput.value = true
    } else {
      errorOnlrInput.value = true
    }

    if (ruleForm.weight_decay === '{}') {
      errorOnWeightDecayInput.value = true
    } else {
      errorOnWeightDecayInput.value = false
    }

    return;
  }
  Promise.all(list)
    .then(async () => {
      await createRuns(projectId, projectDatas, submitObj).then((res) => {
        ElMessageBox.alert('新增训练任务完成', '提示', {
          confirmButtonText: '知道了',
          autofocus: false
        }).then(() => {
          if (store.quickStart.quickFlow) {
            putQuickStartFlow(projectId, { stage: 5 }).finally(()=>{
              store.setQuickModelTitle({title:res.data.title,id:res.data.id})
              router.push({ name: 'quick-start', params: { project_id: projectId } })
            })
          } else {
            router.push({ name: 'model-manage', params: { project_id: projectId } })
          }
        })
      }).finally(() => {
        console.log('success')
      });//调用接口
    })
}

// const submitForm = async (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   await formEl.validate((valid, fields) => {
//     if (valid) {
//       router.push({ name: 'model-manage-submit', params: { project_id: projectId } })
//       // delete ruleForm.modelId
//       // delete ruleForm.sources
//       modelStore().setModelobj(ruleForm)
//     } else {
//       console.log('error submit!', fields)
//     }
//   })
// }

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  router.push({ name: 'model-manage', params: { project_id: projectId } })
}
// 获取所有算法
const allAlg = ref(null);
function AlgAllList() {
  getAlgAllList(projectId).then((res: any) => {
    allAlg.value = Object.assign(res.data)
  }).catch(error => {
    console.log(error)
  })
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: var(--nav-bg-color);
  height: 46px;

  ::v-deep .el-breadcrumb {
    display: flex;
    align-items: center;
  }
}

.wrapBox {
  padding: 0 !important;

  .content {
    margin: 0 20px;

    .title {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
      background-color: #fff;
      color: #333;
      font-weight: bold;
      text-align: left;
      line-height: 24px;
      border-bottom: 2px solid #f6f8fa;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;

      .demo-tabs {
        margin-top: 40px;
      }
    }
  }
}

.el-form-item__error {
  margin-left: 285px;
}


//input type为textarea去掉右下角的两个杠
::v-deep textarea {
  resize: none !important;
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 12px !important;
  color: #c9cdd4 !important;
  margin-top: 2px !important;
}

//面包屑字体颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}

::v-deep .el-tabs__active-bar {
  display: none;
}

::v-deep .el-breadcrumb__inner.is-link,
.el-breadcrumb__inner a {
  font-weight: normal !important;
}

//end
.borderBox {
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #cccccc;
  border-bottom: none;
  padding: 0 5px;
  word-break: break-all;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;

  &:first-child {
    border-radius: 4px 4px 0 0;
  }

  &:last-child {
    border-bottom: 1px solid #cccccc;
    border-radius: 0 0 4px 4px;
  }
}

.rightBox {
  text-align: left;
}

.cpuDataBox {
  color: #585858;

  .title {
    font-size: 12px;
    color: #666;
  }
}

.colorBox {
  color: #585858;

  i {
    display: inline-block;
    font-size: 12px;
    font-style: initial;
    margin-left: 5px;
    transform: scale(0.9);
    transform-origin: left bottom;

  }
}

.inputBox {
  width: 100%;
  border: none;
  height: 30px;
  border: none;
  color: #585858;

  &:focus {
    border: none;
    outline: none;

  }
}

.addValue {
  width: 300px;
  font-size: 25px;

  ::v-deep .el-input__wrapper {
    box-shadow: none !important;
  }

  ::v-deep .el-input__suffix {
    display: none !important;
  }
}
</style>
